using System;
using System.Collections.Generic;
using UnityEngine;
using Voodoo.Pattern;

public class GemSpawner : MonoBehaviour
{
	[SerializeField]
	private GameObject _brick;

	[SerializeField]
	private GameObject _key;

	private List<GameObject> _bricksPool = new List<GameObject>();

	private GameObject key;

	private DateTime lastSpawnTime
	{
		get
		{
			if (long.TryParse(NintendoPlayerPrefs.GetString("Last_Key_Spawn", ""), out var result))
			{
				return DateTime.FromBinary(result);
			}
			lastSpawnTime = DateTime.Now;
			return DateTime.Now;
		}
		set
		{
			NintendoPlayerPrefs.SetString("Last_Key_Spawn", value.ToBinary().ToString() ?? "");
		}
	}

	private void OnDestroy()
	{
		if (key != null)
		{
			UnityEngine.Object.Destroy(key);
		}
	}

	public void SpawnKey(List<Transform> bricks)
	{
		if (key != null)
		{
			UnityEngine.Object.Destroy(key);
		}
		if (!Preloader.ChestRoomConfig.IsEnabled || !((DateTime.Now - lastSpawnTime).TotalMinutes >= 3.0))
		{
			return;
		}
		lastSpawnTime = DateTime.Now;
		key = UnityEngine.Object.Instantiate(_key);
		Vector3 position = default(Vector3);
		foreach (Transform item in bricks.GetRandomRange(5))
		{
			position += item.transform.position;
		}
		position /= 5f;
		key.transform.position = position;
	}

	public void SpawnGems(List<Transform> bricks)
	{
		if (SingletonMB<GameManager>.Instance.IsDuelMode || !Preloader.WallGemsConfig.IsEnabled)
		{
			return;
		}
		for (int i = 0; i < _bricksPool.Count; i++)
		{
			_bricksPool[i].transform.parent = null;
			_bricksPool[i].gameObject.SetActive(value: false);
		}
		int num = bricks.Count / 300;
		List<int> list = new List<int>();
		for (int j = 0; j < num; j++)
		{
			int item = UnityEngine.Random.Range(0, bricks.Count);
			if (!list.Contains(item))
			{
				list.Add(item);
			}
		}
		for (int k = 0; k < list.Count; k++)
		{
			GameObject obj = Brick();
			obj.transform.parent = bricks[list[k]];
			obj.transform.localScale = Vector3.one;
			obj.transform.localPosition = Vector3.zero;
			obj.SetActive(value: true);
			bricks[list[k]].tag = "Gem";
		}
	}

	private void SpawnKey()
	{
	}

	private GameObject Brick()
	{
		for (int i = 0; i < _bricksPool.Count; i++)
		{
			if (!_bricksPool[i].activeInHierarchy)
			{
				return _bricksPool[i];
			}
		}
		GameObject gameObject = UnityEngine.Object.Instantiate(_brick);
		_bricksPool.Add(gameObject);
		return gameObject;
	}
}
